import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { Form, Input, DatePicker, Button, Select, InputNumber, Divider, Typography } from 'antd';
import { SearchOutlined, EnvironmentOutlined, UserOutlined, CalendarOutlined, ControlOutlined, ArrowRightOutlined } from '@ant-design/icons';
import moment, { Moment } from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Text } = Typography;

// 搜索框容器
const SearchBoxContainer = styled.div`
  background-color: #fff;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  margin-bottom: 30px;
`;

// 搜索表单
const SearchForm = styled(Form)`
  .ant-form-item {
    margin-bottom: 16px;
  }
  
  .ant-btn-primary {
    height: 48px;
    font-size: 16px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 500;
    
    .anticon {
      margin-left: 8px;
      font-size: 14px;
    }
  }
  
  .ant-input, .ant-picker, .ant-select-selector {
    border-radius: 8px;
    height: 48px;
  }
  
  .ant-select-selector {
    display: flex;
    align-items: center;
  }
  
  .ant-picker-input > input {
    height: 46px;
  }
  
  .ant-form-item-label > label {
    font-weight: 500;
    color: #262626;
  }
`;

// 表单项布局
const FormLayout = styled.div`
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10px;
  
  .form-col {
    padding: 0 10px;
    flex: 1;
    min-width: 200px;
    margin-bottom: 10px;
    
    &.destination {
      flex: 2;
      min-width: 300px;
    }
    
    &.date-range {
      flex: 2;
      min-width: 300px;
    }
    
    &.submit-button {
      display: flex;
      align-items: flex-end;
    }
  }
`;

// 表单项标题
const FormItemLabel = styled.div`
  font-weight: 600;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  
  .anticon {
    margin-right: 8px;
    color: #1890ff;
    font-size: 16px;
  }
`;

// 高级搜索栏
const AdvancedSearch = styled.div`
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #f0f0f0;
`;

// 高级搜索标题
const AdvancedSearchTitle = styled.div`
  font-weight: 500;
  margin-bottom: 20px;
  cursor: pointer;
  color: #1890ff;
  display: flex;
  align-items: center;
  
  .anticon {
    margin-right: 8px;
    transition: transform 0.3s;
    
    &.expanded {
      transform: rotate(180deg);
    }
  }
  
  &:hover {
    color: #40a9ff;
  }
`;

// 搜索框标题
const SearchTitle = styled.h2`
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #262626;
  text-align: center;
`;

interface SearchBoxProps {
  initialValues?: {
    destination?: string;
    dateRange?: [Moment, Moment];
    guests?: number;
    rooms?: number;
    priceRange?: [number, number];
  };
  onSearch?: (values: any) => void;
}

const SearchBox: React.FC<SearchBoxProps> = ({ initialValues, onSearch }) => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [showAdvanced, setShowAdvanced] = useState(false);
  
  // 默认日期范围（今天和明天）
  const defaultDateRange: [Moment, Moment] = [
    moment(),
    moment().add(1, 'days')
  ];
  
  const handleSearch = (values: any) => {
    const searchParams = {
      ...values,
      checkInDate: values.dateRange?.[0]?.format('YYYY-MM-DD'),
      checkOutDate: values.dateRange?.[1]?.format('YYYY-MM-DD'),
      dateRange: undefined, // 移除dateRange，因为已经拆分为checkInDate和checkOutDate
    };
    
    if (onSearch) {
      onSearch(searchParams);
    } else {
      // 构建查询字符串
      const queryString = new URLSearchParams();
      Object.entries(searchParams).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== '') {
          queryString.append(key, String(value));
        }
      });
      
      // 导航到搜索结果页
      navigate(`/hotels?${queryString.toString()}`);
    }
  };
  
  return (
    <SearchBoxContainer>
      <SearchTitle>找到心仪的酒店</SearchTitle>
      <SearchForm
        form={form}
        initialValues={{
          destination: initialValues?.destination || '',
          dateRange: initialValues?.dateRange || defaultDateRange,
          guests: initialValues?.guests || 2,
          rooms: initialValues?.rooms || 1,
          minPrice: initialValues?.priceRange?.[0],
          maxPrice: initialValues?.priceRange?.[1]
        }}
        onFinish={handleSearch}
      >
        <FormLayout>
          <div className="form-col destination">
            <FormItemLabel>
              <EnvironmentOutlined />
              目的地/酒店名称
            </FormItemLabel>
            <Form.Item name="destination">
              <Input 
                placeholder="城市、行政区、商圈或酒店名" 
                size="large" 
                prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
              />
            </Form.Item>
          </div>
          
          <div className="form-col date-range">
            <FormItemLabel>
              <CalendarOutlined />
              入住和离店日期
            </FormItemLabel>
            <Form.Item name="dateRange" rules={[{ required: true, message: '请选择入住和离店日期' }]}>
              <RangePicker 
                size="large" 
                style={{ width: '100%' }} 
                format="YYYY-MM-DD"
                placeholder={['入住日期', '离店日期']}
                disabledDate={current => current && current < moment().startOf('day')}
              />
            </Form.Item>
          </div>
          
          <div className="form-col">
            <FormItemLabel>
              <UserOutlined />
              住客数
            </FormItemLabel>
            <Form.Item name="guests">
              <Select size="large" style={{ width: '100%' }}>
                {[1, 2, 3, 4, 5, 6].map(num => (
                  <Option key={num} value={num}>{num}人</Option>
                ))}
              </Select>
            </Form.Item>
          </div>
          
          <div className="form-col submit-button">
            <Form.Item>
              <Button type="primary" htmlType="submit" block size="large">
                搜索酒店 <ArrowRightOutlined />
              </Button>
            </Form.Item>
          </div>
        </FormLayout>
        
        <div style={{ textAlign: 'center', marginTop: 6 }}>
          <Text 
            type="secondary" 
            style={{ cursor: 'pointer' }}
            onClick={() => setShowAdvanced(!showAdvanced)}
          >
            {showAdvanced ? '收起高级选项 ∧' : '展开高级选项 ∨'}
          </Text>
        </div>
        
        {showAdvanced && (
          <AdvancedSearch>
            <FormLayout>
              <div className="form-col">
                <FormItemLabel>房间数</FormItemLabel>
                <Form.Item name="rooms">
                  <Select size="large" style={{ width: '100%' }}>
                    {[1, 2, 3, 4, 5].map(num => (
                      <Option key={num} value={num}>{num}间</Option>
                    ))}
                  </Select>
                </Form.Item>
              </div>
              
              <div className="form-col">
                <FormItemLabel>最低价格</FormItemLabel>
                <Form.Item name="minPrice">
                  <InputNumber 
                    size="large" 
                    style={{ width: '100%' }} 
                    min={0} 
                    step={50}
                    placeholder="￥"
                    addonBefore="￥"
                  />
                </Form.Item>
              </div>
              
              <div className="form-col">
                <FormItemLabel>最高价格</FormItemLabel>
                <Form.Item name="maxPrice">
                  <InputNumber 
                    size="large" 
                    style={{ width: '100%' }} 
                    min={0} 
                    step={50}
                    placeholder="￥"
                    addonBefore="￥"
                  />
                </Form.Item>
              </div>
              
              <div className="form-col">
                <FormItemLabel>酒店星级</FormItemLabel>
                <Form.Item name="rating">
                  <Select size="large" style={{ width: '100%' }} placeholder="任意星级">
                    <Option value="5">五星/豪华</Option>
                    <Option value="4">四星/高档</Option>
                    <Option value="3">三星/舒适</Option>
                    <Option value="2">二星/经济</Option>
                  </Select>
                </Form.Item>
              </div>
            </FormLayout>
          </AdvancedSearch>
        )}
      </SearchForm>
    </SearchBoxContainer>
  );
};

export default SearchBox; 